<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Order extends Backend {

	public function __construct()
	{
		parent::__construct();
		$this->lang->load('sites');
		$this->load->model(['site_model','sitecategory_model','goods_model','siteproduct_model','siteuser_model','siteorder_model','sitedisapproved_model']);
		$this->data['page_home']  = lang('lang_dashboard');
		$this->data['page_title'] = lang('lang_site');
		
		$this->data['statetype']=[
			"1"=>'未付款',
			"2"=>'已付款',
			"3"=>'采购中',
			"4"=>'已发货',
			"5"=>'已完成',
			"6"=>'取消',
			"7"=>'退货',
			"8"=>'付款出错',
			"9"=>'ECHECK',
			"10"=>'BACKORDER'
		];
		$this->data['statelabel']=[
			"1"=>'label-danger',
			"2"=>'label-success',
			"3"=>'label-primary',
			"4"=>'label-info',
			"5"=>'label-info',
			"6"=>'label-warning',
			"7"=>'label-warning',
			"8"=>'label-danger',
			"9"=>'label-warning',
		];

	}


	public function index($siteid)
	{

		$site=$this->site_model->getitembyid($siteid);
		if(!$site) die('error link');


		$this->data['nav']=$this->get_site_nav($site,4);

		$this->data['checkapi']=$this->mysite->checklink;

		$this->data['site']=$site;
		// Title
		$this->data['meta_title'] = $this->data['page_title'];

		// Breadcrumbs
		$this->data['array_breadcrumbs'] = array(
			$this->data['page_home']  => 'backend',
			$this->data['page_title'] => 'backend/sites/site',
			'站点订单'=>'backend/sites/order'
		);

		$key=trim($this->input->get('keyword'));
        $uid=trim($this->input->get('uid'));
        $page=max(1,(int) $this->input->get('page'));        
        $pagesize=intval($this->input->get('pagesize'));
        if($pagesize){
            set_cookie("pagesize",$pagesize,60*60*24);
        }else{
            $pagesize=get_cookie("pagesize");
		}
		$page_data=$this->siteorder_model->getpage($siteid,$page,$pagesize,$key,$uid,'0');
		$this->data['loglist']=$page_data["data"];
		$this->data['pager']=$page_data["pager"]; 
		$this->data['total']=$page_data["total"];
        $this->data['pages']=$page_data["pages"];
		$this->data['page']=$page;   
		   
		$keyword = array(
			'name'      => 'keyword',
			'id'        => 'keyword',
			'value'     =>  $key,
			'class'     =>  'form-control input-sm',
			'placeholder'=> '请输入关键字',
			'maxlength' => '100'
		);
		$this->data['keyword']=$keyword;
		

		$this->data['content_header_title'] = content_header_title($this->data['page_title'],$site['name'].' 订单');
		$this->data['content'] = 'sites/order';

		$this->render();
	}

	public function addproduct($id)
	{
		$json=["status"=>0,"msg"=>""];
		$order=$this->siteorder_model->getitembyid($id);
        if($order)
        {
			if($order["productinfo"])
			{
				$newproducts=json_decode($order["productinfo"],true);
			}
			else
			{
				$newproducts=[];
			}
			$pname=$this->input->post("pname");
			if(strstr($pname,"#"))
			{
				$tmp=explode("#",$pname);
				$title=$tmp[0];
			}
			else
			{
				$title=$pname;
			}
			$where=" siteid=".$order["siteid"]." and title='".$title."'";
			$sitepro=$this->siteproduct_model->getitemkeyfilter($where);
			if($sitepro)
			{
				$baseproduct=$this->goods_model->getbyid($sitepro["productid"]);
				$baseimg="";
				$baseurl="#";
				if($baseproduct)
				{
					$baseproduct["thumb"]=unserialize($baseproduct["thumb"]);
					$baseimg=$baseproduct["thumb"][0];
					$baseurl=$baseproduct["source_url"];
				}
				$newproducts[]=[
					"name"=>$pname,
					"quantity"=>1,
					"thumb"=>$baseimg,
					"url"=>$baseurl,
					"price"=>$sitepro["price"],
					"rid"=>$sitepro["rid"],
					"siteurl"=>$sitepro["url"],
				];
				$newdata=["productinfo"=>json_encode($newproducts,JSON_UNESCAPED_UNICODE)];
				if(empty($order["thumb"]))
				{
					$newdata["thumb"]=$baseimg;
				}
				$this->siteorder_model->update($order["id"],$newdata);
				
				$this->siteproduct_model->addsell($sitepro["id"],1);
				if($baseproduct) $this->goods_model->addsell($baseproduct["id"],1);
				$json["status"]=1;
			}
			else
			{
				$json["msg"]="没有找到产品，请检查标题";
			}
		}
		else
		{			
			$json["msg"]="订单不存在";
		}

		echo json_encode($json,JSON_UNESCAPED_UNICODE);
		die();
	}

	public function detail($id)
	{

		$config = $this->systemconfig_model->get_configs(); 
		$order=$this->siteorder_model->getitembyid($id);
        if($order)
        {
			$order["productinfo"]=json_decode($order["productinfo"],true);    
			foreach($order["productinfo"] as &$pro)
			{
				$localres=$this->siteproduct_model->getsitepro($order["siteid"],$pro["rid"]);
				if($localres)
				{
					$pro["localid"]=$localres["productid"];
				}
				else
				{
					$pro["localid"]=0;
				}
			}      
		}
		$checkcount = $this->siteorder_model->checkuserordercount($order);
		$this->data['checkcount']=$checkcount;
		$this->data['config']=$config;
		$this->data['order']=$order;
		$site=$this->site_model->getitembyid($order["siteid"]);
		$this->data['site']=$site;
		$this->data['content'] = 'sites/orderdetail';
		$this->clean_render();
				
	}

	public function ajaxshopping()
	{
		$return=["status"=>1];
		$cid=$this->input->post("cid");
		$order=$this->siteorder_model->getitembyid($cid);
		if(!$order)
		{
			$return["status"]=0;
			$return["msg"]="记录不存在";
		}
		else
		{
			if($order["state"]!=2)
			{
				$return["status"]=0;
				$return["msg"]="只有付款的订单可以进行此操作";
			}
			else
			{
				$ordersn = trim($this->input->post("ordersn"));
				$buyamount = floatval($this->input->post("buyamount"));
				$ordersn = str_replace(["，"," "],",",$ordersn);
				$ordernum = explode(",",$ordersn);
				$ordernum = count($ordernum);
				$source = $this->input->post("source");
				if($source=="weixin" && $buyamount>0)
				{
					$buyamount=round($buyamount/7,2);
				}
				$newdata=[
					"buy_source"=>$source,
					"buy_ordersn"=>trim($ordersn),
					"buy_shipnum"=>trim($this->input->post("shipsn")),
					"shipcount"=>$ordernum,
					"buyamount"=>$buyamount,
					"state"=>3
				];
				$this->siteorder_model->update($order["id"],$newdata);
			}
		}
		echo json_encode($return);
        die();
	}


	public function reset($cid)
	{
		$return=["status"=>1];
		$order=$this->siteorder_model->getitembyid($cid);
		if(!$order)
		{
			$return["status"]=0;
			$return["msg"]="记录不存在";
		}
		else
		{
			if(in_array($order["state"],[3,4]))
			{
				$newdata=[
					"state"=>2,
					"shipcount"=>0,
					"shipping"=>"",
					"buy_ordersn"=>"",
					"buy_source"=>""
				];
				$this->siteorder_model->update($cid, $newdata);
			}
		}
	}


	public function cancel($cid)
	{
		$return=["status"=>1];
		$order=$this->siteorder_model->getitembyid($cid);
		if(!$order)
		{
			$return["status"]=0;
			$return["msg"]="记录不存在";
		}
		else
		{
			if(!in_array($order["state"],[1,2,8]))
			{
				if($order["state"]==3)
				{
					$this->siteorder_model->update($order["id"],["state"=>2,"buy_source"=>"","buy_ordersn"=>"","buy_shipnum"=>"","shipcount"=>0]);
					$msg="订单已经重置为已付款状态";
				}
				else
				{
					$msg="只有付款和未付款的订单可以取消";
				}
				$return["status"]=0;
				$return["msg"]=$msg;
			}
			else
			{
				$site=$this->site_model->getitembyid($order["siteid"]);
				loadsystemlink($site);
				if(!$this->mysite->checklink)
				{
					$return["status"]=0;
					$return["msg"]="请检查接口配置";	
				}
				else
				{
					$result = $this->mysite->cancel($order["oid"]);
					if($result=="ok")
					{
						$this->siteorder_model->update($order["id"],["state"=>6]);
					}
					else
					{
						$return["status"]=0;
						$return["msg"]="取消失败 ".$result;	
					}
				}
			}
			
		}
		echo json_encode($return);
        die();
	}

	public function refresh($cid)
	{
		$return=["status"=>1];
		$order=$this->siteorder_model->getitembyid($cid);
		if(!$order)
		{
			$return["status"]=0;
			$return["msg"]="记录不存在";			
		}
		else
		{
			if($order["state"]!=1)
			{
				$return["status"]=0;
				$return["msg"]="已付款订单，无需刷新";
			}
			else
			{
				$site=$this->site_model->getitembyid($order["siteid"]);
				loadsystemlink($site);
				if(!$this->mysite->checklink)
				{
					$return["status"]=0;
					$return["msg"]="请检查接口配置";	
				}
				else
				{
					$result = $this->mysite->refresh($order["oid"]);
					if($result=="2")
					{
						payorder($order);
						$maxoid=$this->siteorder_model->max("id","");
						$newoid=$maxoid++;
						$this->siteorder_model->update($order["id"],["state"=>2,"id"=>$newoid,"addtime"=>date("Y-m-d H:i:s")]);
					
					}
					else
					{
						$return["status"]=0;
						$return["msg"]="订单当前状态 ".$this->data['statetype'][$result];	
					}
				}
			}
			
		}
		echo json_encode($return);
        die();
	}

	public function newajaxedit()
	{
		$return=["status"=>1];
        $attrName=$this->input->post("attrName");
		$newHtml=$this->input->post("newHtml");
		if(!in_array($attrName,['buy_ordersn','address1','address2','realname','city','provineiso','zipcode','countryiso','phone','email'])) die();
		$cid=$this->input->post("cid");
		$order=$this->siteorder_model->getitembyid($cid);
		if(!$order)
		{
			$return["status"]=0;
			$return["msg"]="记录不存在";			
		}
		else
		{
			if(empty($newHtml))
			{
				$newdata[$attrName]="";
				$newdata["buy_source"]="";
				$newdata["state"]=2;
				$this->siteorder_model->update($cid, $newdata);
			}
			else
			{
				$newdata[$attrName]=$newHtml;
				$this->siteorder_model->update($cid, $newdata);
			}
		}

	}
	
    public function ajaxedit()
    {
		$return=["status"=>1];
        $attrName=$this->input->post("attrName");
		$newHtml=$this->input->post("newHtml");
		if(!in_array($attrName,['note','shipping'])) die();
		$cid=$this->input->post("cid");
		$ordersn = $this->input->post("ordersn");
		$trackurl = $this->input->post("trackurl");
		if($cid)
		{
			$order=$this->siteorder_model->getitembyid($cid);
		}
		else
		{
			$order=$this->siteorder_model->getitembyordersn($ordersn);
			if($order)
			{
				$cid=$order["id"];
			}
		}
		if(!$order || empty($newHtml))
		{
			$return["status"]=0;
			$return["msg"]="记录不存在,数据不能为空";			
		}
		else
		{
			if(in_array($order["state"],[1,5,6,7,8]) && $attrName=="shipping")
			{
				$return["status"]=0;
				$return["msg"]="未付款订单无法发货";	
			}
			else if($attrName=="shipping")
			{

				if($newHtml==$order["shipping"])
				{
					$return["status"]=0;
					$return["msg"]="请勿重复发货";	
				}
				else
				{
					if(!preg_match('/^[0-9a-zA-Z]+$/',$newHtml))
					{
						$return["status"]=0;
						$return["msg"]="订单号包含非法字符";	
					}
					else
					{
						$site=$this->site_model->getitembyid($order["siteid"]);
						loadsystemlink($site);
						if(!$this->mysite->checklink)
						{
							$return["status"]=0;
							$return["msg"]="请检查接口配置";	
						}
						else
						{
							$newdata[$attrName]=$newHtml;
							$newdata["state"]=4;
							$newdata["shipcount"]=$order["shipcount"]-1;

							if($trackurl)
							{
								$newdata["trackurl"]=$trackurl;
							}
							$result = $this->mysite->shiporder($order["oid"],$newHtml);
							if($result=="ok")
							{
								$this->siteorder_model->update($cid, $newdata);
							}
							elseif($result=="nolocation")
							{
								$return["status"]=0;
								$return["msg"]="请先设定一个发货地点，才可以发货";	
							}
						}
					}
				}
				
			}
			else
			{
				$newdata[$attrName]=$newHtml;
				$this->siteorder_model->update($cid, $newdata);
			}			
		}

        echo json_encode($return);
        die();
	}

	public function export()
	{
		$siteid=$this->input->get('siteid');
		$orders =  $this->siteorder_model->getall();
		if($orders)
		{
			$this->makenewxlsx($orders);
		}
		die();
	}

    private function makenewxlsx($data)
    {


        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet()->setTitle(date("Y-m-d").'询盘列表');

        $field=["站点id","真实姓名","邮箱","电话","数量","留言","时间","ip地址","来源"];
        $i=0;
        foreach ($field as $key => $value) {
            $sheet->getColumnDimension(num2alpha($i))->setAutoSize(true);
            $sheet->setCellValue(num2alpha($i).'1', $value);
            $i++;
        }
        $rowcount=1;
        if($data):
            foreach($data as $k=>$item)
            {
                $rowcount++;
                $v=[$item["siteid"],$item["realname"],$item["email"],$item["phone"],$item["quantity"],$item["info"],date("Y-m-d",strtotime($item["addtime"])),$item["ipaddr"],$item["url"]];
                $i=0;
                foreach($field as $key=>$value){
                    $sheet->getCell(num2alpha($i++).$rowcount)->setValueExplicit(
                        $v[$key],
                        \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING
                    );
                }

            }
        endif;

        $writer = new Xlsx($spreadsheet);
        $filename=date("Y-m-d.H/i/s")."询盘列表.xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
        die();
    }
    //老导出execl方法，已弃用
//	private function makexlsx($data)
//	{
//
//		$this->load->helper(array('ihttp'));
//		$spreadsheet = new Spreadsheet();
//        $sheet = $spreadsheet->getActiveSheet()->setTitle(date("Y-m-d").'网站询盘');
//
//        $field=["ID","真实姓名","邮箱","电话","数量","留言","时间","IP地址	","来源","备注"];
//        $i=0;
//        foreach ($field as $key => $value) {
//            if($i!=2) $sheet->getColumnDimension(num2alpha($i))->setAutoSize(true);
//            $sheet->setCellValue(num2alpha($i).'1', $value);
//            $i++;
//		}
//		$sheet->getColumnDimension("C")->setWidth(135);
//		$rowcount=1;
//		if($data):
//			foreach($data as $k=>$item)
//			{
//				//if($item["state"]>3) continue;
//				$productinfo=json_decode($item["productinfo"],true);
//				foreach($productinfo as $vc=>$pro){
//
//
//
//					if($pro["thumb"]){
//						if(strstr($pro["thumb"],"?v="))
//						{
//							$tmpimg=explode("?v=",$pro["thumb"]);
//							$pro["thumb"]=$tmpimg[0];
//						}
//					}
//					$rowcount++;
//					$sheet->getRowDimension($rowcount)->setRowHeight(90);
//					$v=[$item["ordersn"],isset($pro["variant"])?$pro["variant"]:'','',$pro["quantity"],"1",$item["realname"],$item["address1"],$item["address2"],$item["city"],$item["provineiso"],$item["countryiso"],$item["zipcode"],$item["phone"],'',''];
//					$i=0;
//					foreach($field as $key=>$value){
//						$sheet->getCell(num2alpha($i++).$rowcount)->setValueExplicit(
//							$v[$key],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING
//						);
//					}
//
//					if($pro["thumb"])
//                    {
//                        $imgua=explode(".",$pro["thumb"]);
//                        $ext=array_pop($imgua);
//                        //$ext="jpg";
//                        $fullname="./upload/pro/".date("Ymd")."/".$item["id"]."_".$vc.".".$ext;
//                        if(!file_exists($fullname))
//                        {
//                            $url = trim($pro["thumb"]);
//                            $resp = ihttp_get($url);
//                            mkdirs(dirname($fullname));
//                            file_put_contents($fullname, $resp['content']);
//                        }
//
//                        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
//                        $drawing->setName('pro');
//                        $drawing->setDescription('pro');
//                        $drawing->setHeight(1);
//                        $drawing->setWidth(100);
//                        $drawing->setOffsetX(10);
//                        $drawing->setOffsetY(10);
//                        $drawing->setPath($fullname);
//                        $drawing->setCoordinates("C".$rowcount);
//                        $drawing->setWorksheet($spreadsheet->getActiveSheet());
//                    }
//				}
//			}
//
//		endif;
//
//
//        $writer = new Xlsx($spreadsheet);
//        $filename=date("Y-m-d")."发货清单.xlsx";
//        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//        header('Content-Disposition: attachment;filename="'.$filename.'"');
//        header('Cache-Control: max-age=0');
//		$writer->save('php://output');
//		die();
//	}

}
